const { Service } = require('egg');
const { getSqlCount, getSqlSelect } = require('../utils/sql')


class CompanyService extends Service {
  async getSqlList(param, type = 'get') {
    return await this.app.mysql[type]('company_list', param)
  }

  // 详情
  async detail(param) {
    const result = await this.getSqlList(param)
    return result
  }
  // 创建
  async create(param) {
    const nParam = Object.assign({}, param, {
      create_time: new Date().valueOf(),
      user_id: this.ctx.userId
    })
    const result = await this.getSqlList(nParam, 'insert');
    const updateSuccess = result.affectedRows === 1;
    return updateSuccess
  }
  // 更新
  async update(param) {
    const nParam = Object.assign({}, param, {
      update_time: new Date().valueOf()
    })
    const result = await this.getSqlList(nParam, 'update')
    const updateSuccess = result.affectedRows === 1;
    return updateSuccess
  }
  // 删除
  async delete(param) {
    if (!param.id) return false
    const result = await this.getSqlList({ id: param.id }, 'delete');
    const updateSuccess = result.affectedRows === 1;
    return updateSuccess
  }

  // 分页查询
  async select(param) {
    const where = {
      company_name: {
        type: 'like',
        val: param.company_name
      },
      department_name: {
        type: 'like',
        val: param.department_name
      },
      position_name: {
        type: 'like',
        val: param.position_name
      },
      create_time: {
        type: 'range',
        val: param.create_time
      }
    }
    Object.keys(where).forEach(key => {
      if (!where[key].val) {
        delete where[key]
      }
    })
    const countSql = getSqlCount('company_list', { where })
    const countList = await this.app.mysql.query(countSql)
    const count = countList[0]['count(1)']
    const sql = getSqlSelect('company_list', {
      where,
      orders: [[ 'create_time', 'desc' ]],
      limit: param.pageSize, // 返回数据量
      offset: param.current, // 数据偏移量
    })
    console.log(sql)
    const result = await this.app.mysql.query(sql)
    return {
      total: count,
      list: result
    };
  }
}

module.exports = CompanyService;
